<template>
  <div class="basic-tab-container">
    <!-- 供应商基本信息 Group -->
    <el-card class="info-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="title-wrapper">
            <span class="title-text">供应商基本信息</span>
            <el-tag :type="supplier.enabled ? 'success' : 'danger'" size="small" class="status-tag">
              {{ supplier.enabled ? '启用' : '停用' }}
            </el-tag>
          </div>
          <el-button type="primary" size="small" @click="showEditDialog" v-if="hasEditPermission">
            编辑
          </el-button>
        </div>
      </template>

      <el-descriptions :column="3">
        <el-descriptions-item label="供应商名称">{{ supplier.name || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ supplier.contactName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ supplier.contactPhoneNumber || '-' }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ supplier.email || '-' }}</el-descriptions-item>
        <el-descriptions-item label="城市">{{ supplier.city || '-' }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ supplier.address || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ supplier.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 账户信息 Group -->
    <el-card class="finance-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="title-wrapper">
            <span class="title-text">账户信息</span>
          </div>
          <el-button type="primary" size="small" @click="showEditDialog" v-if="hasEditPermission">
            编辑
          </el-button>
        </div>
      </template>

      <el-table :data="filterFundAccount(supplier.fundAccount)" style="width: 100%" border>
        <el-table-column prop="name" label="账户名称" width="180"></el-table-column>

        <el-table-column prop="balance" label="账户余额" width="120">
          <template #default="scope">
            <span v-if="isMetalAccount(scope.row)">
              {{ formatMetal(scope.row.balance) }}
            </span>
            <span v-else>
              {{ formatCurrency(scope.row.balance) }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 编辑对话框  -->
    <supplier-basic-info-dialog ref="editDialog" mode="edit" @submit="handleEditSubmit" />

  </div>
</template>

<script>
import { Supplier } from '../../public/engine/targetOrg/supplier'
import { BasicUiAction } from '../../public/engine/uiAction/basicUiAction'
import SupplierBasicInfoDialog from './supplierBasicInfoDialog.vue'
import { ElMessage } from 'element-plus'
import { Util } from '../../public/utils/util'
import { AppTheme } from '../../public/theme/appTheme'
import { FundAccountInsideType } from '../../public/engine/common/fundDefinition'


export default {
  name: 'SupplierBasicTabPage',
  components: {
    SupplierBasicInfoDialog
  },
  props: {
    supplierId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      supplier: new Supplier(),
      receivableAmount: 0,
      payableAmount: 0,
      lastTransactionDate: '',
      creditLimit: 0,
      showEditDialogVisible: false,
      fundColor: AppTheme.foundStringColor,
      metalColor: AppTheme.foundStringBlueColor,
      loading: false,
    }
  },
  computed: {
    hasEditPermission() {
      // 根据实际权限系统调整
      return true
    }
  },
  async created() {
    await this.loadSupplierData()
    await this.loadFinancialData()
  },
  methods: {
    async loadSupplierData() {
      try {
        this.loading = true
        const res = await new BasicUiAction().getSupplierDetailInfo(this.supplierId)
        if (res) {
          this.supplier = res
        }
      } catch (error) {
        console.error('加载供应商数据失败:', error)
        ElMessage.error('加载供应商数据失败')
      } finally {
        this.loading = false
      }
    },
    async loadFinancialData() {
      try {
        // 模拟财务数据 - 替换为实际API调用
        this.receivableAmount = 12500.78
        this.payableAmount = 5800.32
        this.lastTransactionDate = '2023-06-15'
        this.creditLimit = 50000
      } catch (error) {
        console.error('加载财务数据失败:', error)
      }
    },
    formatCurrency(value) {
      return `¥${value.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`
    },
    formatMetal(value) {
      return `${value.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')} 克`
    },
    showEditDialog() {
      console.log('Opening dialog') // 添加调试日志
      // 通过 ref 调用子组件的 open 方法
      this.$refs.editDialog.open(this.supplier);
    },

    handleEditSubmit({ type, data }) {
      if (type === 'update') {
        ElMessage.success('供应商信息更新成功')
        this.loadSupplierData() // 刷新数据

        // 通知detail page
        this.$emit('basicInfoUpdated', this.supplier);
      }
    },

    isMetalAccount(fundAccount) {
      if (fundAccount && fundAccount.accountType && fundAccount.accountType.code === FundAccountInsideType.ObjMetalAccount.code) {
        return true;
      }
      return false;
    },

    ignoreAccount(fundAccount) {
      if (fundAccount && fundAccount.accountType && fundAccount.accountType.code === FundAccountInsideType.ObjFundAccount.code) {
        fundAccount.name = "存欠款";
      }

      if (fundAccount && fundAccount.accountType &&
        (fundAccount.accountType.code === FundAccountInsideType.AdvReceiveAccount.code || fundAccount.accountType.code === FundAccountInsideType.AdvPaymentAccount.code)) {
        return true;
      }
      return false;
    },

    filterFundAccount(fundAccountList) {
      return fundAccountList.filter(fundAccount => !this.ignoreAccount(fundAccount));
    }
  }
}
</script>

<style scoped>
.basic-tab-container {
  padding: 10px;
}

.supplier-detail-container {
  padding: 20px;
  max-width: 1000px;
  /* 保留最大宽度限制 */
  margin-right: auto;
  /* 改为右侧自动，实现左对齐 */
}

.info-card {
  margin-bottom: 20px;
  min-width: 800px;
  max-width: 100%;
  border-radius: 10px;
  /* 添加圆角效果 */
}

.finance-card {
  margin-bottom: 20px;
  min-width: 800px;
  max-width: 100%;
  border-radius: 8px;
  /* 添加圆角效果 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

}

.title-wrapper {
  display: flex;
  align-items: center;
  gap: 18px;
}

.title-text {
  font-size: 16px;
  font-weight: bold;
}

.status-tag {
  margin-left: 0;
  font-size: 12px;
}

.amount {
  font-weight: bold;
  color: v-bind(fundColor);
  /* 使用JavaScript变量 */
}

.metailAmount {
  font-weight: bold;
  color: v-bind(metalColor);
  /* 使用JavaScript变量 */
}

.metalAmount {
  font-weight: bold;
  color: #409EFF;
}

.finance-card .el-descriptions-item {
  padding: 12px 10px;
}

.finance-content {
  padding: 12px;
}

.finance-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.finance-label {
  flex: 0 0 120px;
  /* 固定标签宽度 */
  text-align: left;
  font-weight: normal;
  color: #606266;
}
</style>